package com.guli.gulimall.gulimallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.guli.common.utils.ProductConstant;
import com.guli.gulimall.gulimallproduct.dao.AttrAttrgroupRelationDao;
import com.guli.gulimall.gulimallproduct.dao.AttrGroupDao;
import com.guli.gulimall.gulimallproduct.dao.CategoryDao;
import com.guli.gulimall.gulimallproduct.entity.AttrAttrgroupRelationEntity;
import com.guli.gulimall.gulimallproduct.entity.AttrGroupEntity;
import com.guli.gulimall.gulimallproduct.entity.CategoryEntity;
import com.guli.gulimall.gulimallproduct.service.CategoryService;
import com.guli.gulimall.gulimallproduct.service.ProductAttrValueService;
import com.guli.gulimall.gulimallproduct.vo.AttrGroupRelationVo;
import com.guli.gulimall.gulimallproduct.vo.AttrRespVo;
import com.guli.gulimall.gulimallproduct.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;
import com.guli.gulimall.gulimallproduct.dao.AttrDao;
import com.guli.gulimall.gulimallproduct.entity.AttrEntity;
import com.guli.gulimall.gulimallproduct.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
@Transactional
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao; //商品属性DAO
    @Autowired
    private CategoryDao categoryDao;//商品分类dao
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //获取key
        String key = (String) params.getOrDefault("key", null);
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<AttrEntity>();

        if (!key.isEmpty()) {
            attrEntityQueryWrapper.eq("attr_id", key).or().like("attr_name", key);
        }
        System.out.println(key);
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                attrEntityQueryWrapper
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //保存基本数据
        this.save(attrEntity);
        //保存关联关系,只有为基本关系才保存
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()&&attr.getAttrId()!=null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }

    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catId, String attr_type) {
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(attr_type) ?
                ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        //查所有
        if (catId != 0) {
            attrEntityQueryWrapper.eq("catelog_id", catId);
        }
        String key = params == null ? "" : (String) params.get("key");
        if (key != null && !key.isEmpty() && key != "") {
            attrEntityQueryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key)
                        .or().like("attr_name", key)
                        .or().like("search_type", key)
                        .or().like("show_desc", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                attrEntityQueryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVoStream = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //1设置分类和分组的名字
            if ("base".equalsIgnoreCase(attr_type)) {
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                String groupName = relationEntity != null ? attrGroupDao.selectById(relationEntity.getAttrGroupId()).getAttrGroupName() : "";
                attrRespVo.setGroupName(groupName);
            }
            String cateName = categoryDao.selectById(attrRespVo.getCatelogId()).getName();
            attrRespVo.setCatelogName(cateName);
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVoStream);
        return pageUtils;
    }

    /**
     * 根据分组id查找所有关联到的属性
     *
     * @param attr_group_id
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attr_group_id) {
        List<AttrAttrgroupRelationEntity> relationEntities = this.attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attr_group_id));
        List<Long> attrId = relationEntities.stream().map((attr) -> attr.getAttrId()).collect(Collectors.toList());
        if (attrId == null || attrId.size() == 0) return null;
        Collection<AttrEntity> attrEntities = this.listByIds(attrId);
        return (List<AttrEntity>) attrEntities;
    }

    /**
     * 获取当前id没有关联的属性
     *
     * @param attr_group_id
     * @param params
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Long attr_group_id, Map<String, Object> params) {
//        List<AttrAttrgroupRelationEntity> relationEntities = this.attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().neq("attr_group_id", attr_group_id));
        //1 当前id只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_group_id);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2只能关联别的分组里自己不关联的
        //找到当前分类下的其他分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));

        List<Long> collect = attrGroupEntities.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //这些分组关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attriDS = relationEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        QueryWrapper<AttrEntity> attrEntityList = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attriDS != null && attriDS.size() > 0) {
            attrEntityList.notIn("attr_id", attriDS);
        }
        String key = (String) params.get("key");
        if (key.isEmpty() == false) {
            attrEntityList.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrEntityList);
        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrids) {
        //SELECT * FROM pms_attr WHERE attr_id IN(?) AND search_type =1
        return  this.baseMapper.selectSearchAttrs(attrids);
    }


    @Transactional
    @Override
    public void deleRelation(AttrGroupRelationVo[] vos) {
        attrAttrgroupRelationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", 1L).eq("attr_group_id", 1L));
        //
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((arvo) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(arvo, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        System.out.println(entities);
        attrAttrgroupRelationDao.deleteBatchRalation(entities);
    }


    @Override
    public AttrRespVo getAttrInfor(Long attrId) {
        AttrRespVo vo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, vo);
        //只有是基本属性才有分组信息
        if (vo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity atRaletion = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (atRaletion != null) {
                vo.setAttrGroupId(atRaletion.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(atRaletion.getAttrGroupId());
                if (null != attrGroupEntity) {
                    vo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //设置分类信息，完整路径
        Long catelogoId = vo.getCatelogId();
        CategoryEntity categoryEntity = categoryDao.selectById(catelogoId);
        vo.setCatelogName(categoryEntity == null ? "" : categoryEntity.getName());
        vo.setCatelogPath(categoryService.findCatelogPath(catelogoId));
        BeanUtils.copyProperties(attrEntity, vo);
        return vo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //修改分组关联
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            Long count = attrAttrgroupRelationDao.selectCount(new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {

                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

}